// 处理歌曲url
export const processSongUrl = (songs: ISongItem[], urls: ISongUrlItem[]): ISongItem[] => {
  return songs.map((song) => {
    const findUrl = urls.find((url) => url.id === song.id)
    findUrl && (song.rtUrl = findUrl.url)
    return song
  })
}
// 处理歌曲背景图片
export const processSongPic = (songs: ISongItem[], data: ISongItem[]) => {
  return songs.map((song) => {
    const findUrl = data.find((item) => item.id === song.id)
    findUrl && (song.al.picUrl = findUrl.al.picUrl)
    return song
  })
}

// 随机播放 (洗牌算法)
const getRandomInt = (max: number) => Math.floor(Math.random() * (max + 1))

const swap = (arr: any[], i: number, j: number) => {
  const t = arr[i]
  arr[i] = arr[j]
  arr[j] = t
}
export const shuffle = <T = any>(source: T[]) => {
  const arr = source.slice()
  for (let i = 0; i < arr.length; i++) {
    const j = getRandomInt(i)
    swap(arr, i, j)
  }
  return arr
}

/** px 转 vmin, 375 是设置的屏幕宽度 */
export const px2vmin = (px: number): string => `${(px / 375) * 100}vmin`

// 当前设备是移动设备
export const isMobile = () => /Mobi|Android|iPhone/i.test(navigator.userAgent)

// 毫秒转换为 mm:ss 格式
export const formatMilliseconds = (value: number): string => {
  let second = value / 1000 // second
  let minute = 0 // minute
  if (second > 60) {
    minute = second / 60
    second = second % 60
    if (minute > 60) {
      minute = minute % 60
    }
  }
  let result: string
  if (second >= 10) {
    result = '' + second.toFixed(0)
  } else {
    result = '' + '0' + second.toFixed(0)
  }
  if (minute >= 10) {
    result = '' + minute.toFixed(0) + ':' + result
  } else {
    result = '' + '0' + minute.toFixed(0) + ':' + result
  }
  return result
}

// 防抖
export const debounce = (fn: (param?: any) => any, delay: number = 300) => {
  let timer: number | undefined
  return function (this: unknown, ...args: any) {
    const context = this
    clearTimeout(timer)
    timer = setTimeout(function () {
      fn.apply(context, args)
    }, delay)
  }
}

//节流
export const throttle = (fn: (param?: any) => any, delay: number = 300) => {
  let oldTime = Date.now()
  return function (this: unknown, ...args: any) {
    const newTime = Date.now()
    if (newTime - oldTime >= delay) {
      fn.apply(this, args)
      oldTime = Date.now()
    }
  }
}

//  判断是安卓还是苹果浏览器
export const getBrowserPlatform = () => ({
  isAndroid: Boolean(navigator.userAgent.match(/android/gi)), // 是否是Android浏览器
  isIphone: Boolean(navigator.userAgent.match(/iphone|ipod|iOS/gi)), // 是否是苹果浏览器
  isIpad: Boolean(navigator.userAgent.match(/ipad/gi)), // 是否是 IPad 浏览器
  isWeixin: Boolean(navigator.userAgent.match(/MicroMessenger/gi)), // 是否是微信平台浏览器
  isAli: Boolean(navigator.userAgent.match(/AlipayClient/gi)), // 是否是支付宝平台浏览器
  isPhone: Boolean(/(iPhone|iPad|iPod|iOS|Android)/i.test(navigator.userAgent)) // 是否是手机端
})
